package org.itboys.mobile.service.mongo.weixin;

import org.apache.commons.collections.map.HashedMap;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayActivity;
import org.itboys.mobile.entity.mongo.SundayApply;
import org.itboys.mobile.service.mongo.web.SundayActivityService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：贾琦磊
 * @Date：2018/7/12
 * @Description：用户报名接口
 */
@Service
public class SundayWeiXinApplyService extends BaseMongoService<SundayApply> {
    @Resource(name = "mobileDs")
    private MongoDataSource dataSource;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return dataSource;
    }

    @Override
    protected Class<SundayApply> getEntityClass() {
        return SundayApply.class;
    }

    @Autowired
    private SundayActivityService activityService;
    @Autowired
    private SundayValicodedateService valicodedateService;

    /**
     * 新增报名
     * @param memberId
     * @param name
     * @param weChat
     * @param num
     * @param activityId
     */
    public void save(Long memberId, String name, String mobile, String weChat, Integer num, Long activityId,String code) throws Exception {

        valicodedateService.checkValidateCode(mobile,code);

        SundayActivity activity = activityService.getById(activityId);
        //判断活动是否结束
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date today = new Date();
        Date eDate = sdf.parse(activity.geteDate());
        if (eDate.getTime() < today.getTime()) {
            throw new ErrorException("活动已结束");
        }
        //判断用户是否已经报名
        if (isApply(mobile, activityId)) {
            throw new ErrorException("不可重复报名");
        }
        SundayApply apply = new SundayApply(memberId, name, mobile, weChat, num, activityId, SundayCommonConstants.NO);
        super.save(apply);
    }

    /**
     * 判断用户是否已经报名
     *
     * @param mobile
     * @param activityId
     * @return
     */
    public boolean isApply(String mobile, Long activityId) {
        Map param = new HashMap<>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("mobile", mobile);
        param.put("activityId", activityId);
        List applys = super.list(param);
        return ListUtil.isNotNull(applys);
    }

}